package com.yuhanginfo.modules.web.web;


import java.util.Date;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.security.shiro.session.SessionDAO;
import com.yuhanginfo.common.utils.CookieUtils;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.common.utils.UserAgentUtils;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.modules.web.entity.WebLoginInfo;
import com.yuhanginfo.modules.web.enums.LoginType;
import com.yuhanginfo.modules.web.security.UserRealm.Principal;
import com.yuhanginfo.modules.web.security.UsernamePasswordToken;
import com.yuhanginfo.modules.web.service.WebLoginInfoService;
import com.yuhanginfo.modules.web.util.WebUserUtils;

/**
 * 登录Controller
 * 
 * @author YuHangInfo
 * @version 2013-5-31
 */
@Controller
public class WebLoginController extends BaseController {

	@Autowired
	private SessionDAO sessionDAO;
	
	@Autowired
	private WebLoginInfoService loginInfoService;
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${frontPath}/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = WebUserUtils.getUserPrincipal();

		if (logger.isDebugEnabled()) {
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}

		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))) {
			CookieUtils.setCookie(response, "LOGINED", "false");
		}

		// 如果已经登录，则跳转到管理首页
		if (principal != null && !principal.isMobileLogin()) {
			return "redirect:"+Global.getFrontPath()+"/webIndex";
		}
		return "modules/web/webLogin";
	}

	/**
	 *
	 */
	@RequestMapping(value = "${frontPath}/login", method = RequestMethod.POST)
	public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model,HttpSession session) {
		Date now = new Date();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String black = "";
		if (password==null){
			password = black;
		}
		boolean rememberMe = this.isRememberMe(request);
		String host = StringUtils.getRemoteAddr((HttpServletRequest) request);
		String captcha = request.getParameter("validateCode");
		boolean mobile = isMobileLogin(request);
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken customizedToken = new UsernamePasswordToken(username, password.toCharArray(),
					rememberMe, host, captcha, mobile, LoginType.USER.toString());
			customizedToken.setRememberMe(false);
			try {
				currentUser.login(customizedToken);
				session.setAttribute("webUser", WebUserUtils.getYongUser());
				WebLoginInfo loginInfo = new WebLoginInfo();
				loginInfo.setLoginName(username);
				loginInfo.setLoginIp(UserAgentUtils.getIpAddr(request));
				loginInfo.setBrowserName(UserAgentUtils.getRequestBrowserInfo(request));
				loginInfo.setEquipment(UserAgentUtils.getDeviceType(request).getName());
				loginInfo.setCreateDate(now);
				loginInfo.setUpdateDate(now);
				loginInfoService.save(loginInfo);
				return "redirect:"+Global.getFrontPath()+"/webIndex";
			} catch (IncorrectCredentialsException ice) {
				logger.error(ice.getMessage(),ice);
				model.addAttribute("returnCode", "0");
				model.addAttribute("returnMessage", "您输入的账号或密码不匹配，请重新输入");
			} catch (LockedAccountException lae) {
				logger.error(lae.getMessage(),lae);
				model.addAttribute("returnCode", "0");
				model.addAttribute("returnMessage", "账户已被冻结");
			} catch (AuthenticationException ae) {
				logger.error(ae.getMessage(),ae);
				model.addAttribute("returnCode", "0");
				model.addAttribute("returnMessage", "您输入的账号或密码不匹配，请重新输入");
			}
		}else{
			return "redirect:"+Global.getFrontPath()+"/webIndex";
		}
		
		return "modules/web/webLogin";
	}

	/**
	 * 登出
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${frontPath}/logout")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		WebUserUtils.getSubject().logout();
		return "redirect:"+Global.getFrontPath()+"/webIndex";
	}

	/**
	 * 登出
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${frontPath}/logoutLogin")
	public String logoutLogin(HttpServletRequest request, HttpServletResponse response) {
		WebUserUtils.getSubject().logout();
		return "modules/web/webLogin";
	}
	
	protected boolean isRememberMe(ServletRequest request) {
		String isRememberMe = request.getParameter("isRememberMe");
		return StringUtils.toBoolean(isRememberMe);
	}

	protected boolean isMobileLogin(ServletRequest request) {
		String value = request.getParameter("mobileLogin");
		return value != null && returnIsMobileLogin(value);
	}
	/**
	 * 解决表达式不应该太复杂
	 */
	private boolean returnIsMobileLogin(String value){
		return returnIsMobileLogin1(value) || returnIsMobileLogin2(value) || returnIsMobileLogin3(value);
	}

	private boolean returnIsMobileLogin1(String value) {
		return "true".equalsIgnoreCase(value) || "t".equalsIgnoreCase(value);
	}
	private boolean returnIsMobileLogin2(String value) {
		return "1".equalsIgnoreCase(value) || "enabled".equalsIgnoreCase(value);
	}
	private boolean returnIsMobileLogin3(String value) {
		return "y".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value);
	}
	
}
